<?php

use think\Db;
	/**
	 * 生成订单号
	 */
	function order_create_no(){
		return date('YmdHis', time()).rand(8, true);
	}
	/**
	 * XML编码
	 * @param mixed $data 数据
	 * @param string $encoding 数据编码
	 * @param string $root 根节点名
	 * @return string
	 */
	function xml_encode($data, $encoding='utf-8', $root='think') {
		header('Content-Type:text/xml; charset=utf-8');
	    $xml    = '<?xml version="1.0" encoding="' . $encoding . '"?>';
	    $xml   .= '<' . $root . '>';
	    $xml   .= data_to_xml($data);
	    $xml   .= '</' . $root . '>';
	    return $xml;
	}
/**
 * 判断是不是今天
 */
function isToday($datetime){
	$time = date('Y-m-d', strtotime($datetime));
	if ($time == date('Y-m-d', time())) {
	   return true;
	} else {
	    return false;
	}
}
function isWeek($datetime){
	$dt_s= date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y")))."\n";
	$dt_e= date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y")))."\n";
	if($datetime>$datetime&&$datetime<$dt_e){
		return true;
	}
	return false;
}
	/**
	 * 数据XML编码
	 * @param mixed $data 数据
	 * @return string
	 */
	function data_to_xml($data) {
	    $xml = '';
	    foreach ($data as $key => $val) {
	        is_numeric($key) && $key = "item id=\"$key\"";
	        $xml    .=  "<$key>";
	        $xml    .=  ( is_array($val) || is_object($val)) ? data_to_xml($val) : $val;
	        list($key, ) = explode(' ', $key);
	        $xml    .=  "</$key>";
	    }
	    return $xml;
	}
/* 
 * 加密--32位密码
 */
function md5_salt($password) {
	return md5(crypt($password, config('salt')));
}

/**
 * 返回格式化后的当前时间
 */
function now_time(){
	return date('Y-m-d H:i:s',time());
}

/**
 * 获得配置
 */
function get_config($name){
	$site_config = db('system')->field('value')->where('name', $name)->find();
    $site_config = unserialize($site_config['value']);
	return $site_config;
}

/**
 * 获取微信操作对象
 * @staticvar array $wechat
 * @param type $type
 * @return WechatReceive
 */
function load_wechat($type = '')
{
    $wechat = array();
	$index = md5(strtolower($type));
	if (!isset($wechat[$index])) {
    	$config = get_config('wechat_config');
    	$config['cachepath'] = CACHE_PATH . 'wechat';
    	$wechat[$index] = Wechat\Loader::get($type, $config);
	}
	return $wechat[$index];
}
function load_agent_wechat($type = '',$config)
{
    $wechat = array();
	$index = md5(strtolower($type));
	if (!isset($wechat[$index])) {
    	$config = get_config('wechat_config');
    	$config['cachepath'] = CACHE_PATH . 'wechat';
    	$wechat[$index] = Wechat\Loader::get($type, $config);
	}
	return $wechat[$index];
}
/**
 * 设置全局配置到文件
 *
 * @param $key
 * @param $value
 * @return boolean
 */
function sys_config_setbykey($key, $value)
{
    $file = ROOT_PATH.'application/extra/log.php';
    $cfg = array();
    if (file_exists($file)) {
        $cfg = include $file;
    }
    $item = explode('.', $key);
    switch (count($item)) {
        case 1:
            $cfg[$item[0]] = $value;
            break;
        case 2:
            $cfg[$item[0]][$item[1]] = $value;
            break;
    }
    return file_put_contents($file, "<?php\nreturn " . var_export($cfg, true) . ";");
}
/**
 * 设置全局配置到文件
 *
 * @param array
 * @return boolean
 */
function sys_config_setbyarr($data)
{
    $file = ROOT_PATH.'application/extra/log.php';
    if(file_exists($file)){
        $configs=include $file;
    }else {
        $configs=array();
    }
    $configs=array_merge($configs,$data);
    return file_put_contents($file, "<?php\treturn " . var_export($configs, true) . ";");
}
/**
 * 获取全局配置
 *
 * @param $key
 * @return array|null
 */
function sys_config_get($key)
{
    $file = ROOT_PATH.'application/extra/log.php';
    $cfg = array();
    if (file_exists($file)) {
        $cfg = (include $file);
    }
    return isset($cfg[$key]) ? $cfg[$key] : null;
}

/**
 * 获取当前request参数数组,去除值为空
 * @return array
 */
function get_query(){
	$param = request()->except(['s']);
	$rst = array();
	foreach($param as $k=>$v){
		if(!empty($v)){
			$rst[$k] = $v;
		}
	}
	return $rst;
}

/**
 * 是否存在方法
 * @param string $module 模块
 * @param string $controller 待判定控制器名
 * @param string $action 待判定控制器名
 * @return number 方法结果，0不存在控制器 1存在控制器但是不存在方法 2存在控制和方法
 */
function has_action($module, $controller, $action){
	$controller = $controller . 'Controller';
	$arr = cache('controllers'.'_'.$module);
	if(empty($arr)){
		$arr = \ReadClass::readDir(APP_PATH . $module. DS .'controller');
		cache('controllers'.'_'.$module,$arr);
	}
    if((!empty($arr[$controller])) && $arr[$controller]['class_name'] == $controller ){
		$method_name = array_map('array_shift',$arr[$controller]['method']);
        if(in_array($action, $method_name)){
           return 2;
        }else{
           return 1;
        }
    }else{
        return 0;
    }
}

/**
 * 获取客户端操作系统信息包括win10
 * @return string
 */
function getOs()
{
	$agent = $_SERVER['HTTP_USER_AGENT'];

	if (preg_match('/win/i', $agent) && strpos($agent, '95')) {
		$os = 'Windows 95';
	} else if (preg_match('/win 9x/i', $agent) && strpos($agent, '4.90')) {
		$os = 'Windows ME';
	} else if (preg_match('/win/i', $agent) && preg_match('/98/i', $agent)) {
		$os = 'Windows 98';
	} else if (preg_match('/win/i', $agent) && preg_match('/nt 6.0/i', $agent)) {
		$os = 'Windows Vista';
	} else if (preg_match('/win/i', $agent) && preg_match('/nt 6.1/i', $agent)) {
		$os = 'Windows 7';
	} else if (preg_match('/win/i', $agent) && preg_match('/nt 6.2/i', $agent)) {
		$os = 'Windows 8';
	} else if (preg_match('/win/i', $agent) && preg_match('/nt 10.0/i', $agent)) {
		$os = 'Windows 10';#添加win10判断
	} else if (preg_match('/win/i', $agent) && preg_match('/nt 5.1/i', $agent)) {
		$os = 'Windows XP';
	} else if (preg_match('/win/i', $agent) && preg_match('/nt 5/i', $agent)) {
		$os = 'Windows 2000';
	} else if (preg_match('/win/i', $agent) && preg_match('/nt/i', $agent)) {
		$os = 'Windows NT';
	} else if (preg_match('/win/i', $agent) && preg_match('/32/i', $agent)) {
		$os = 'Windows 32';
	} else if (preg_match('/linux/i', $agent)) {
		$os = 'Linux';
	} else if (preg_match('/unix/i', $agent)) {
		$os = 'Unix';
	} else if (preg_match('/sun/i', $agent) && preg_match('/os/i', $agent)) {
		$os = 'SunOS';
	} else if (preg_match('/ibm/i', $agent) && preg_match('/os/i', $agent)) {
		$os = 'IBM OS/2';
	} else if (preg_match('/Mac/i', $agent)) {
		$os = 'Mac';
	} else if (preg_match('/PowerPC/i', $agent)) {
		$os = 'PowerPC';
	} else if (preg_match('/AIX/i', $agent)) {
		$os = 'AIX';
	} else if (preg_match('/HPUX/i', $agent)) {
		$os = 'HPUX';
	} else if (preg_match('/NetBSD/i', $agent)) {
		$os = 'NetBSD';
	} else if (preg_match('/BSD/i', $agent)) {
		$os = 'BSD';
	} else if (preg_match('/OSF1/i', $agent)) {
		$os = 'OSF1';
	} else if (preg_match('/IRIX/i', $agent)) {
		$os = 'IRIX';
	} else if (preg_match('/FreeBSD/i', $agent)) {
		$os = 'FreeBSD';
	} else if (preg_match('/teleport/i', $agent)) {
		$os = 'teleport';
	} else if (preg_match('/flashget/i', $agent)) {
		$os = 'flashget';
	} else if (preg_match('/webzip/i', $agent)) {
		$os = 'webzip';
	} else if (preg_match('/offline/i', $agent)) {
		$os = 'offline';
	} elseif (preg_match('/ucweb|MQQBrowser|J2ME|IUC|3GW100|LG-MMS|i60|Motorola|MAUI|m9|ME860|maui|C8500|gt|k-touch|X8|htc|GT-S5660|UNTRUSTED|SCH|tianyu|lenovo|SAMSUNG/i', $agent)) {
		$os = 'mobile';
	} else {
		$os = '未知操作系统';
	}
	return $os;
}

/**
 * 获取客户端浏览器信息 添加win10 edge浏览器判断
 * @author  Jea杨
 * @return string
 */
function getBroswer()
{
	$sys = $_SERVER['HTTP_USER_AGENT'];  //获取用户代理字符串
	if (stripos($sys, "Firefox/") > 0) {
		preg_match("/Firefox\/([^;)]+)+/i", $sys, $b);
		$exp[0] = "Firefox";
		$exp[1] = $b[1];  //获取火狐浏览器的版本号
	} elseif (stripos($sys, "Maxthon") > 0) {
		preg_match("/Maxthon\/([\d\.]+)/", $sys, $aoyou);
		$exp[0] = "傲游";
		$exp[1] = $aoyou[1];
	} elseif (stripos($sys, "MSIE") > 0) {
		preg_match("/MSIE\s+([^;)]+)+/i", $sys, $ie);
		$exp[0] = "IE";
		$exp[1] = $ie[1];  //获取IE的版本号
	} elseif (stripos($sys, "OPR") > 0) {
		preg_match("/OPR\/([\d\.]+)/", $sys, $opera);
		$exp[0] = "Opera";
		$exp[1] = $opera[1];
	} elseif (stripos($sys, "Edge") > 0) {
		//win10 Edge浏览器 添加了chrome内核标记 在判断Chrome之前匹配
		preg_match("/Edge\/([\d\.]+)/", $sys, $Edge);
		$exp[0] = "Edge";
		$exp[1] = $Edge[1];
	} elseif (stripos($sys, "Chrome") > 0) {
		preg_match("/Chrome\/([\d\.]+)/", $sys, $google);
		$exp[0] = "Chrome";
		$exp[1] = $google[1];  //获取google chrome的版本号
	} elseif (stripos($sys, 'rv:') > 0 && stripos($sys, 'Gecko') > 0) {
		preg_match("/rv:([\d\.]+)/", $sys, $IE);
		$exp[0] = "IE";
		$exp[1] = $IE[1];
	} elseif (stripos($sys, 'Safari') > 0) {
		preg_match("/safari\/([^\s]+)/i", $sys, $safari);
		$exp[0] = "Safari";
		$exp[1] = $safari[1];
	} else {
		$exp[0] = "未知浏览器";
		$exp[1] = "";
	}
	return $exp[0] . '(' . $exp[1] . ')';
}
 
/**
 * 短信发送
 * $mobile 手机号
 * $tempalte 短信模板ID
 * $params 参数
 */
function send_sms($mobile, $template_id, $params, $sign_name,$content=null){
	// 获取短信配置
	$sms_config = get_config('sms_config');
	include_once ('./vendor/alidayu/TopSdk.php');
    date_default_timezone_set('Asia/Shanghai');
	$c = new TopClient;
//	$c -> format = 'json';
//	$c -> simplify = true;
	$c -> appkey = $sms_config['app_key'];
	$c -> secretKey = $sms_config['app_secret'];
	$req = new AlibabaAliqinFcSmsNumSendRequest;
	$req -> setSmsType("normal");
	if($sign_name){
		$req -> setSmsFreeSignName($sign_name);
	}else{
		$req->setSmsFreeSignName("龙信天下");
	}
	if($params){
		$req -> setSmsParam($params);
	}
	$req -> setRecNum($mobile);
	if($content){
		$req->setSmsParam('{"customer":"'.$content.'"}');
	}
	$req -> setSmsTemplateCode($template_id);
	$resp = $c -> execute($req);
	return $resp;
}

/**
 * 短信验证
 * $mobile 手机号
 * $code 验证码
 * $template_no 短信模板编号
 */
function check_code($mobile, $code, $template_no){
	$template = db('sms_template') -> find($template_no);
	$sms_config = get_config('sms_config');
	$where['mobile'] = $mobile;
	$where['title'] = $template['title']; 
	$where['result'] = 1;
	$result = db('sms_code') -> where($where) -> order('add_time desc')-> find();
	if($result){
		//判断是否正确
		if($code == $result['code']){
			// 短信有效期
			if(time() < strtotime($result['add_time']) + $sms_config['verify_time']){
				return 1;
			}
		}
	}
	return -1;
}

/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 * @author rainfer <81818832@qq.com>
 */
function format_bytes($size, $delimiter = '') {
    $units = array(' B', ' KB', ' MB', ' GB', ' TB', ' PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 数组层级缩进转换
 * @param array $array
 * @param int   $pid
 * @param int   $level
 * @return array
 */
function array2level($array, $pid = 0, $level = 1) {
    static $list = [];
    foreach ($array as $v) {
        if ($v['pid'] == $pid) {
            $v['level'] = $level;
            $list[]     = $v;
            array2level($array, $v['id'], $level + 1);
        }
    }

    return $list;
}

/**
 * 构建层级（树状）数组
 * @param array  $array 要进行处理的一维数组，经过该函数处理后，该数组自动转为树状数组
 * @param string $pid 父级ID的字段名
 * @param string $child_key_name 子元素键名
 * @return array|bool
 */
function array2tree(&$array, $pid = 'pid', $child_key_name = 'children') {
    $counter = array_children_count($array, $pid);
    if ($counter[0] == 0)
        return false;
    $tree = [];
    while (isset($counter[0]) && $counter[0] > 0) {
        $temp = array_shift($array);
        if (isset($counter[$temp['id']]) && $counter[$temp['id']] > 0) {
            array_push($array, $temp);
        } else {
            if ($temp[$pid] == 0) {
                $tree[] = $temp;
            } else {
                $array = array_child_append($array, $temp[$pid], $temp, $child_key_name);
            }
        }
        $counter = array_children_count($array, $pid);
    }

    return $tree;
}

/**
 * 子元素计数器
 * @param $array
 * @param $pid
 * @return array
 */
function array_children_count($array, $pid) {
    $counter = [];
    foreach ($array as $item) {
        $count = isset($counter[$item[$pid]]) ? $counter[$item[$pid]] : 0;
        $count++;
        $counter[$item[$pid]] = $count;
    }

    return $counter;
}

/**
 * 把元素插入到对应的父元素$child_key_name字段
 * @param        $parent
 * @param        $pid
 * @param        $child
 * @param string $child_key_name 子元素键名
 * @return mixed
 */
function array_child_append($parent, $pid, $child, $child_key_name) {
    foreach ($parent as &$item) {
        if ($item['id'] == $pid) {
            if (!isset($item[$child_key_name]))
                $item[$child_key_name] = [];
            $item[$child_key_name][] = $child;
        }
    }

    return $parent;
}

/**
 * 循环删除目录和文件
 * @param string $dir_name
 * @return bool
 */
function delete_dir_file($dir_name) {
    $result = false;
    if(is_dir($dir_name)){
        if ($handle = opendir($dir_name)) {
            while (false !== ($item = readdir($handle))) {
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir_name . DS . $item)) {
                        delete_dir_file($dir_name . DS . $item);
                    } else {
                        unlink($dir_name . DS . $item);
                    }
                }
            }
            closedir($handle);
            if (rmdir($dir_name)) {
                $result = true;
            }
        }
    }

    return $result;
}

/**
 * 判断是否为手机访问
 * @return  boolean
 */
function is_mobile() {
    static $is_mobile;

    if (isset($is_mobile)) {
        return $is_mobile;
    }

    if (empty($_SERVER['HTTP_USER_AGENT'])) {
        $is_mobile = false;
    } elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false
              || strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false
              || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false
              || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false
              || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false
              || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false
              || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false
    ) {
        $is_mobile = true;
    } else {
        $is_mobile = false;
    }

    return $is_mobile;
}

/**
 * 返回不含前缀的数据库表数组
 * @param bool
 * @return array
 */
function db_get_tables($prefix=false) {
    $db_prefix =config('database.prefix');
    $list  = Db::query('SHOW TABLE STATUS FROM '.config('database.database'));
    $list  = array_map('array_change_key_case', $list);
    $tables = array();
    foreach($list as $k=>$v){
        if(empty($prefix)){
            if(stripos($v['name'],strtolower(config('database.prefix')))===0){
                $tables [] = strtolower(substr($v['name'], strlen($db_prefix)));
            }
        }else{
            $tables [] = strtolower($v['name']);
        }
    }
    return $tables;
}

/**
 * 强制下载
 * @param string $filename
 * @param string $content
 */
function force_download_content($filename, $content) {
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Type: application/force-download");
    header("Content-Transfer-Encoding: binary");
    header("Content-Disposition: attachment; filename=$filename");
    echo $content;
    exit ();
}
/**
 * 返回数据表的sql
 * @param $table : 不含前缀的表名
 * @return string
 */
function db_get_insert_sqls($table) {
    $db_prefix =config('database.prefix');
    $db_prefix_re = preg_quote($db_prefix);
    $db_prefix_holder = '<--db-prefix-->';
    $export_sqls = array();
    $export_sqls [] = "DROP TABLE IF EXISTS $db_prefix_holder$table";
    switch (config('database.type')) {
        case 'mysql' :
            if (!($d = Db::query("SHOW CREATE TABLE $db_prefix$table"))) {
                $this->error("'SHOW CREATE TABLE $table' Error!");
            }
            $table_create_sql = $d [0] ['Create Table'];
            $table_create_sql = preg_replace('/' . $db_prefix_re . '/', $db_prefix_holder, $table_create_sql);
            $export_sqls [] = $table_create_sql;
            $data_rows = Db::query("SELECT * FROM $db_prefix$table");
            $data_values = array();
            foreach ($data_rows as &$v) {
                foreach ($v as &$vv) {
                    //TODO mysql_real_escape_string替换方法
                    //$vv = "'" . @mysql_real_escape_string($vv) . "'";
					$vv = "'" . addslashes(str_replace(array("\r","\n"),array('\r','\n'),$vv)) . "'";
                }
                $data_values [] = '(' . join(',', $v) . ')';
            }
            if (count($data_values) > 0) {
                $export_sqls [] = "INSERT INTO `$db_prefix_holder$table` VALUES \n" . join(",\n", $data_values);
            }
            break;
    }
    return join(";\n", $export_sqls) . ";";
}
/**
 * 不检测表前缀,恢复数据库
 * @param $file
 */
function db_restore_file($file) {
    $db_prefix=config('database.prefix');
    $sqls = file_get_contents($file);
    $sqls = str_replace('<--db-prefix-->', $db_prefix, $sqls);
    $sqlarr = explode(";\n", $sqls);
    foreach ($sqlarr as &$sql) {
        Db::execute($sql);
    }
}
/**
 * 序列化
 */
function iserializer($value) {
	return serialize($value);
}
function iunserializer($value, $default_value = '') {
	if (empty($value)) {
		return $default_value;
	}
	if (!is_serialized($value)) {
		return $value;
	}
	$result = unserialize($value);
	if ($result === false) {
		$temp = preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $value);
		return unserialize($temp);
	}
	return $result;
}
function ihttp_get($url) {
	return ihttp_request($url);
}
function strexists($string, $segment) {
	return !(strpos($string, $segment) === FALSE);
}
function ver_compare($version1, $version2) {
	if(strlen($version1) <> strlen($version2)) {
		$version1_tmp = explode('.', $version1);
		$version2_tmp = explode('.', $version2);
		if(strlen($version1_tmp[1]) == 1) {
			$version1 .= '0';
		}
		if(strlen($version2_tmp[1]) == 1) {
			$version2 .= '0';
		}
	}
	return version_compare($version1, $version2);
}

function ihttp_request($url, $post = '', $extra = array(), $timeout = 60) {
	$urlset = parse_url($url);
	if (empty($urlset['path'])) {
		$urlset['path'] = '/';
	}
	if (!empty($urlset['query'])) {
		$urlset['query'] = "?{$urlset['query']}";
	}
	if (empty($urlset['port'])) {
		$urlset['port'] = $urlset['scheme'] == 'https' ? '443' : '80';
	}
	if (strexists($url, 'https://') && !extension_loaded('openssl')) {
		if (!extension_loaded("openssl")) {
			message('请开启您PHP环境的openssl');
		}
	}
	if (function_exists('curl_init') && function_exists('curl_exec')) {
		$ch = curl_init();
				if (ver_compare(phpversion(), '5.6') >= 0) {
			curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
		}
		if (!empty($extra['ip'])) {
			$extra['Host'] = $urlset['host'];
			$urlset['host'] = $extra['ip'];
			unset($extra['ip']);
		}
		curl_setopt($ch, CURLOPT_URL, $urlset['scheme'] . '://' . $urlset['host'] . ($urlset['port'] == '80' ? '' : ':' . $urlset['port']) . $urlset['path'] . $urlset['query']);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HEADER, 1);
		if ($post) {
			if (is_array($post)) {
				$filepost = false;
				foreach ($post as $name => $value) {
					if (substr($value, 0, 1) == '@' || (class_exists('CURLFile') && $value instanceof CURLFile)) {
						$filepost = true;
						break;
					}
				}
				if (!$filepost) {
					$post = http_build_query($post);
				}
			}
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
		}
		if (!empty($GLOBALS['_W']['config']['setting']['proxy'])) {
			$urls = parse_url($GLOBALS['_W']['config']['setting']['proxy']['host']);
			if (!empty($urls['host'])) {
				curl_setopt($ch, CURLOPT_PROXY, "{$urls['host']}:{$urls['port']}");
				$proxytype = 'CURLPROXY_' . strtoupper($urls['scheme']);
				if (!empty($urls['scheme']) && defined($proxytype)) {
					curl_setopt($ch, CURLOPT_PROXYTYPE, constant($proxytype));
				} else {
					curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
					curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
				}
				if (!empty($GLOBALS['_W']['config']['setting']['proxy']['auth'])) {
					curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS['_W']['config']['setting']['proxy']['auth']);
				}
			}
		}
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($ch, CURLOPT_SSLVERSION, 1);
		if (defined('CURL_SSLVERSION_TLSv1')) {
			curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
		}
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1');
		if (!empty($extra) && is_array($extra)) {
			$headers = array();
			foreach ($extra as $opt => $value) {
				if (strexists($opt, 'CURLOPT_')) {
					@curl_setopt($ch, constant($opt), $value);
				} elseif (is_numeric($opt)) {
					@curl_setopt($ch, $opt, $value);
				} else {
					$headers[] = "{$opt}: {$value}";
				}
			}
			if (!empty($headers)) {
				curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			}
		}
		$data = curl_exec($ch);
		$status = curl_getinfo($ch);
		$errno = curl_errno($ch);
		$error = curl_error($ch);
		curl_close($ch);
		if ($errno || empty($data)) {
			return error(1, $error);
		} else {
			$temp = ihttp_response_parse($data);
			if (in_array($temp['code'], array('301', '302')) && $extra['CURLOPT_FOLLOWLOCATION']) {
				return ihttp_request($temp['headers']['Location'], $post, $extra, $timeout);
			} else {
				return ihttp_response_parse($data);
			}
		}
	}
	$method = empty($post) ? 'GET' : 'POST';
	$fdata = "{$method} {$urlset['path']}{$urlset['query']} HTTP/1.1\r\n";
	$fdata .= "Host: {$urlset['host']}\r\n";
	if (function_exists('gzdecode')) {
		$fdata .= "Accept-Encoding: gzip, deflate\r\n";
	}
	$fdata .= "Connection: close\r\n";
	if (!empty($extra) && is_array($extra)) {
		foreach ($extra as $opt => $value) {
			if (!strexists($opt, 'CURLOPT_')) {
				$fdata .= "{$opt}: {$value}\r\n";
			}
		}
	}
	$body = '';
	if ($post) {
		if (is_array($post)) {
			$body = http_build_query($post);
		} else {
			$body = urlencode($post);
		}
		$fdata .= 'Content-Length: ' . strlen($body) . "\r\n\r\n{$body}";
	} else {
		$fdata .= "\r\n";
	}
	if ($urlset['scheme'] == 'https') {
		$fp = fsockopen('ssl://' . $urlset['host'], $urlset['port'], $errno, $error);
	} else {
		$fp = fsockopen($urlset['host'], $urlset['port'], $errno, $error);
	}
	stream_set_blocking($fp, true);
	stream_set_timeout($fp, $timeout);
	if (!$fp) {
		return error(1, $error);
	} else {
		fwrite($fp, $fdata);
		$content = '';
		while (!feof($fp))
			$content .= fgets($fp, 512);
		fclose($fp);
		return ihttp_response_parse($content, true);
	}
}


function ihttp_response_parse($data, $chunked = false) {
	$rlt = array();
	$headermeta = explode('HTTP/', $data);
	if (count($headermeta) > 2) {
		$data = 'HTTP/' . array_pop($headermeta);
	}
	$pos = strpos($data, "\r\n\r\n");
	$split1[0] = substr($data, 0, $pos);
	$split1[1] = substr($data, $pos + 4, strlen($data));
	
	$split2 = explode("\r\n", $split1[0], 2);
	preg_match('/^(\S+) (\S+) (\S+)$/', $split2[0], $matches);
	$rlt['code'] = $matches[2];
	$rlt['status'] = $matches[3];
	$rlt['responseline'] = $split2[0];
	$header = explode("\r\n", $split2[1]);
	$isgzip = false;
	$ischunk = false;
	foreach ($header as $v) {
		$pos = strpos($v, ':');
		$key = substr($v, 0, $pos);
		$value = trim(substr($v, $pos + 1));
		if (isset($rlt['headers'][$key])&&is_array($rlt['headers'][$key])) {
			$rlt['headers'][$key][] = $value;
		} elseif (!empty($rlt['headers'][$key])) {
			$temp = $rlt['headers'][$key];
			unset($rlt['headers'][$key]);
			$rlt['headers'][$key][] = $temp;
			$rlt['headers'][$key][] = $value;
		} else {
			$rlt['headers'][$key] = $value;
		}
		if(!$isgzip && strtolower($key) == 'content-encoding' && strtolower($value) == 'gzip') {
			$isgzip = true;
		}
		if(!$ischunk && strtolower($key) == 'transfer-encoding' && strtolower($value) == 'chunked') {
			$ischunk = true;
		}
	}
	if($chunked && $ischunk) {
		$rlt['content'] = ihttp_response_parse_unchunk($split1[1]);
	} else {
		$rlt['content'] = $split1[1];
	}
	if($isgzip && function_exists('gzdecode')) {
		$rlt['content'] = gzdecode($rlt['content']);
	}

	$rlt['meta'] = $data;
	if($rlt['code'] == '100') {
		return ihttp_response_parse($rlt['content']);
	}
	return $rlt;
}

function ihttp_response_parse_unchunk($str = null) {
	if(!is_string($str) or strlen($str) < 1) {
		return false; 
	}
	$eol = "\r\n";
	$add = strlen($eol);
	$tmp = $str;
	$str = '';
	do {
		$tmp = ltrim($tmp);
		$pos = strpos($tmp, $eol);
		if($pos === false) {
			return false;
		}
		$len = hexdec(substr($tmp, 0, $pos));
		if(!is_numeric($len) or $len < 0) {
			return false;
		}
		$str .= substr($tmp, ($pos + $add), $len);
		$tmp  = substr($tmp, ($len + $pos + $add));
		$check = trim($tmp);
	} while(!empty($check));
	unset($tmp);
	return $str;
}


function is_base64($str){
	if(!is_string($str)){
		return false;
	}
	return $str == base64_encode(base64_decode($str));
}
/**验证码*/
 function check_sendcode($mobile, $code, $message){
		$where['mobile'] = $mobile;
		$where['code'] = $code;
		$where['message'] = '发送成功';
		$result =db('sms_code')->where($where)->find();
		// 10分钟有效期
		if(time() - strtotime($result['add_time']) > 600){
			return 2;
		}
		if($code == $result['code']){
			return 1;
		}else{
			return -1;
		}
	}
//支付日志
function add_paylog($status,$tid){
	$data = array(
		'type' 			=> $_POST['type'],
		'sn' 			=> $_POST['WIDout_trade_no'],
		'user_type' 	=> $_POST['user_type'],
		'pay_type' 		=> $_POST['pay_type'],
		'tid'			=> $tid,
		'uid'			=> $_POST['uid'],
		'price'			=> ($_POST['WIDtotal_fee'] )* 100,
		'add_time' 		=> 	now_time(),
		'status'		=>$status
	);
	$res=db("mall_paylog")->insert($data);
}
function currency_format($currency, $decimals = 2) {
	$currency = floatval($currency);
	if (empty($currency)) {
		return '0.00';
	}
	$currency = number_format($currency, $decimals);
	$currency = str_replace(',', '', $currency);
	return $currency;
}

/**
 * 获取分销设置
 */
 function getDisbution(){
	return getSiteBname("distribution");
}
//根据设置名字获取设置
function getSiteBname($name){
	if (cache('setting')&&isset(cache('setting')[$name])) {
		$site_config = cache('setting')[$name];
	} else {
		$site_config = db("mall_setting")->where("inc_type",$name)->find();
		$setting[$name]=$site_config;
		cache("setting",$setting);
	}
	return iunserializer($site_config['value']);
}
//根据设置名字获取多个设置
function getListSiteBname($name){
	if (cache('setting')&&isset(cache('setting')[$name])) {
		$site_config = cache('setting')[$name];
	} else {
		$site_config = db("mall_setting")->where("inc_type",$name)->select();
		foreach($site_config as $k=>$v){
			$site_config[$k]['value']=iunserializer($v['value']);
		}
		$setting[$name]=$site_config;
		cache("setting",$setting);
	}
	return $site_config;
}
function is_serialized( $data, $strict = true ) {
	if (!is_string($data)) {
		return false;
	}
	$data = trim($data);
	if ('N;' == $data) {
		return true;
	}
	if (strlen( $data ) < 4) {
		return false;
	}
	if (':' !== $data[1]) {
		return false;
	}
	if ($strict) {
		$lastc = substr($data, -1);
		if (';' !== $lastc && '}' !== $lastc) {
			return false;
		}
	} else {
		$semicolon = strpos($data, ';');
		$brace = strpos($data, '}');
				if (false === $semicolon && false === $brace)
			return false;
				if (false !== $semicolon && $semicolon < 3)
			return false;
		if (false !== $brace && $brace < 4)
			return false;
	}
	$token = $data[0];
	switch ($token) {
		case 's' :
			if ($strict) {
				if ( '"' !== substr( $data, -2, 1 )) {
					return false;
				}
			} elseif (false === strpos( $data, '"')) {
				return false;
			}
					case 'a' :
		case 'O' :
			return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
		case 'b' :
		case 'i' :
		case 'd' :
			$end = $strict ? '$' : '';
			return (bool) preg_match( "/^{$token}:[0-9.E-]+;$end/", $data );
	}
	return false;
}
